package cn.demo.reverseProxy.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @Author: ljh
 * @Date: 2019/10/9 21:29
 * zuul前置过滤器
 */
@Component
public class TrackingFilter extends ZuulFilter {

    private static final boolean SHOULD_FILTER = true;
    private static final Logger log = LoggerFactory.getLogger(TrackingFilter.class);

    /**
     * pre：可以在请求被路由之前调用
     * route：在路由请求时候被调用
     * post：在route和error过滤器之后被调用
     * error：处理请求时发生错误时被调用
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 通过int值来定义过滤器的执行顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 返回一个boolean类型来判断该过滤器是否要执行，所以通过此函数可实现过滤器的开关
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return SHOULD_FILTER;
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        String corrId=genereteUUid();
        context.addZuulRequestHeader("corr_id",corrId);
        UserContextHolder.getContext().setCorrelationId(corrId);
        log.info("url{}",context.getRequest().getRequestURI());
        log.info("创建一个head{}",corrId);
        return null;
    }

    /**
     * 获取头部
     * @return
     */
    private String getHead() {
        RequestContext context = RequestContext.getCurrentContext();
        String head = context.getRequest().getHeader("x-uid");
        if (StringUtils.isNotEmpty(head)){
            return head;
        }else {
            return context.getZuulRequestHeaders().get("x-uid");
        }
    }
    /**
     * 创建uuid
     */
    private String genereteUUid(){
        return UUID.randomUUID().toString();
    }
    /**
     * 在zuul转发得请求中加入uid
     */
    private void setHead(){
        RequestContext context = RequestContext.getCurrentContext();
        context.addZuulRequestHeader("x-uid",genereteUUid());
    }
}
